package com.yikaiye.android.yikaiye.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.DialogGuigeBinding;
import com.yikaiye.android.yikaiye.http.HttpRespond;
import com.yikaiye.android.yikaiye.http.MyObserver;
import com.yikaiye.android.yikaiye.http.RetrofitHelper;
import com.yikaiye.android.yikaiye.model.CheckComboResponseModel;
import com.yikaiye.android.yikaiye.model.CheckModel;
import com.yikaiye.android.yikaiye.model.ChooseServiceModel;
import com.yikaiye.android.yikaiye.model.ProductServiceModel;
import com.yikaiye.android.yikaiye.utils.UMengUtil;
import com.yikaiye.android.yikaiye.widget.flowLayout.FlowLayoutManager;
import com.yikaiye.android.yikaiye.widget.flowLayout.SpaceItemDecoration;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 产品规格
 */
public abstract class ProductFormatDialog {
    private final Dialog dialog;
    private final Context context;
    private final List<ChooseServiceModel> chooseServiceList = new ArrayList<>();
    private final List<ProductServiceModel> serviceList = new ArrayList<>();
    private final String productId;
    private CheckComboResponseModel checkComboResponseModel;
    private LoadingDialog loadingDialog = null;
    private boolean isCanClick = true;
    private final DialogGuigeBinding binding;

    public ProductFormatDialog(Context context, List<ProductServiceModel> serviceInfo, String productId) {
        this.serviceList.addAll(serviceInfo);
        this.productId = productId;
        this.context = context;
        initLoadingDialog();
        binding = DialogGuigeBinding.inflate(LayoutInflater.from(context));
        dialog = new Dialog(context, R.style.prompt_progress_dialog_dimenabled);
        dialog.setContentView(binding.getRoot(), new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        dialog.setCancelable(true);
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow != null) {
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.BOTTOM);
            dialogWindow.setWindowAnimations(R.style.main_menu_animStyle);
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            dialogWindow.setAttributes(lp);
        }
        binding.recyclerView.setAdapter(new ProductFormatAdapter());
        binding.tvConfirmOrder.setOnClickListener(view12 -> {
            UMengUtil.setCountEventId(Constant.DIALOG_ATTR_BUY);
            confirmOrder(checkComboResponseModel);
            dismissDialog();
        });

        binding.ivClose.setOnClickListener(view1 -> dismissDialog());

        for (ProductServiceModel serviceModel : serviceList) {
            ChooseServiceModel chooseServiceModel = new ChooseServiceModel();
            chooseServiceModel.setServiceId(serviceModel.getId());
            chooseServiceModel.setServiceName(serviceModel.getName());
            List<String> remarks = new ArrayList<>();
            for (ProductServiceModel.ServiceAttr serviceAttr : serviceModel.getServiceAttrs()) {
                if (null != serviceAttr.getAttrRemarks() && serviceAttr.getAttrRemarks().size() > 0) {
                    remarks.add(serviceAttr.getAttrRemarks().get(0));
                    chooseServiceModel.setRemarks(remarks);
                }
            }
            if (null != serviceModel.getServiceAttrCycles() && serviceModel.getServiceAttrCycles().size() > 0) {
                chooseServiceModel.setServiceAttrCycle(serviceModel.getServiceAttrCycles().get(0));
            }
            chooseServiceList.add(chooseServiceModel);

            if (serviceModel.getServiceType() == 1) {
                ProductServiceModel.ServiceAttr serviceAttr = new ProductServiceModel.ServiceAttr();
                serviceAttr.setName(context.getString(R.string.buying_cycle));
                serviceAttr.setAttrRemarks(serviceModel.getServiceAttrCycles());
                serviceModel.getServiceAttrs().add(serviceAttr);
            }
        }
        CheckModel checkModel = new CheckModel();
        checkModel.setProductId(productId);
        checkModel.setProductReqs(chooseServiceList);

        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(checkModel));
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkProduct(requestBody), new MyObserver<HttpRespond<CheckComboResponseModel>>() {
            @Override
            protected void onSuccess(HttpRespond<CheckComboResponseModel> httpRespond) {
                if (Constant.SUCCESS == httpRespond.code) {
                    if (null != httpRespond.data) {
                        checkComboResponseModel = httpRespond.data;
                        binding.tvProductPrice.setText(httpRespond.data.getProductPrice());
                        binding.tvConfirmOrder.setBackgroundResource(R.drawable.shape_f93f50_4dp);
                        binding.tvConfirmOrder.setEnabled(true);
                        binding.tvConfirmOrder.setText(context.getString(R.string.confirm_place_order));
                    }
                } else {
                    binding.tvConfirmOrder.setBackgroundResource(R.drawable.shape_d7d7d7_4dp);
                    binding.tvConfirmOrder.setEnabled(false);
                    binding.tvConfirmOrder.setText(context.getString(R.string.not_package));
                }
            }

            @Override
            protected void onFail(Throwable e) {
            }
        });


    }

    /**
     * 确认订单
     */
    public abstract void confirmOrder(CheckComboResponseModel checkComboResponseModel);

    public void showDialog() {
        dialog.show();
    }

    public void dismissDialog() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    class ProductFormatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public ProductFormatAdapter() {
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ProductFormatAdapter.ProductHolder(View.inflate(context, R.layout.item_product_format_layout, null));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            final ProductHolder productHolder = (ProductHolder) holder;
            ProductServiceModel productServiceModel = serviceList.get(position);
            productHolder.title.setText(productServiceModel.getName());
            productHolder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
            productHolder.recyclerView.setAdapter(new ProductFormatAdapter.ServiceAttrAdapter(productServiceModel.getServiceAttrs(), position));
        }

        @Override
        public int getItemCount() {
            return serviceList.size();
        }

        class ProductHolder extends RecyclerView.ViewHolder {
            private final TextView title;
            private final RecyclerView recyclerView;

            public ProductHolder(View itemView) {
                super(itemView);
                title = itemView.findViewById(R.id.title);
                recyclerView = itemView.findViewById(R.id.recyclerView);
            }
        }

        class ServiceAttrAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

            private final List<ProductServiceModel.ServiceAttr> attrData;
            private final int serviceNamePos;

            public ServiceAttrAdapter(List<ProductServiceModel.ServiceAttr> attrData, int serviceNamePos) {
                this.attrData = attrData;
                this.serviceNamePos = serviceNamePos;
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new ServiceAttrAdapter.ServiceAttrHolder(View.inflate(context, R.layout.item_product_format_attr_layout, null));
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                final ServiceAttrHolder mHolder = (ServiceAttrHolder) holder;
                ProductServiceModel.ServiceAttr attrModel = attrData.get(position);
                final FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
                mHolder.title.setText(attrModel.getName());
                if (mHolder.itemView.getTag() == null) {
                    mHolder.recyclerView.addItemDecoration(new SpaceItemDecoration(dp2px(7)));
                    mHolder.itemView.setTag("item");
                }
                mHolder.recyclerView.setLayoutManager(flowLayoutManager);
                mHolder.recyclerView.setAdapter(new ProductFormatAdapter.FlowAdapter(attrModel.getAttrRemarks(), serviceNamePos, position));
            }

            @Override
            public int getItemCount() {
                return attrData.size();
            }

            class ServiceAttrHolder extends RecyclerView.ViewHolder {
                private final TextView title;
                private final RecyclerView recyclerView;

                public ServiceAttrHolder(View itemView) {
                    super(itemView);
                    title = itemView.findViewById(R.id.title);
                    recyclerView = itemView.findViewById(R.id.recyclerView);
                }
            }
        }

        class FlowAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

            private final List<String> list;
            private String mAttrName;
            private final int serviceNamePos;
            private final int attrNamePos;

            public FlowAdapter(List<String> list, int serviceNamePos, int attrNamePos) {
                this.list = list;
                this.serviceNamePos = serviceNamePos;
                this.attrNamePos = attrNamePos;
                if (list.size() > 0) {
                    mAttrName = list.get(0);
                }
            }

            @NotNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
                return new ProductFormatAdapter.FlowAdapter.MyHolder(View.inflate(context, R.layout.flow_item, null));
            }

            @Override
            public void onBindViewHolder(@NotNull RecyclerView.ViewHolder holder, final int position) {
                TextView textView = ((ProductFormatAdapter.FlowAdapter.MyHolder) holder).text;
                String attrName = list.get(position);
                textView.setBackgroundResource(mAttrName.equals(attrName) ? R.drawable.shape_1af93f50_2dp : R.drawable.shape_f7f7f7_2dp);
                textView.setTextColor(mAttrName.equals(attrName) ? 0xFFF93F50 : 0xFF3B3A40);
                ProductServiceModel serviceModel = serviceList.get(serviceNamePos);
                int period = serviceList.get(serviceNamePos).getServicePeriod();

                if (serviceModel.getServiceType() == 1) {
                    if (serviceModel.getServicePeriod() == 12) {
                        textView.setText(attrName.matches("[0-9]+") ? context.getString(R.string.cycle_month_count, attrName) : attrName);
                    } else if (period == 1) {
                        textView.setText(attrName.matches("[0-9]+") ? context.getString(R.string.cycle_year_count, attrName) : attrName);
                    }
                } else {
                    textView.setText(attrName);
                }
                holder.itemView.setOnClickListener(v -> {
                    if (attrName.matches("[0-9]+")) {
                        chooseServiceList.get(serviceNamePos).setServiceAttrCycle(attrName);
                    } else {
                        chooseServiceList.get(serviceNamePos).getRemarks().set(attrNamePos, attrName);
                    }
                    Log.e("@@@@@@@@", new Gson().toJson(chooseServiceList));

                    CheckModel checkModel = new CheckModel();
                    checkModel.setProductId(productId);
                    checkModel.setProductReqs(chooseServiceList);

                    if (isCanClick && !mAttrName.equals(attrName)) {
                        isCanClick = false;
                        RequestBody requestBody =
                                RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(checkModel));
                        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkProduct(requestBody), new MyObserver<HttpRespond<CheckComboResponseModel>>() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            protected void onSuccess(HttpRespond<CheckComboResponseModel> httpRespond) {
                                if (Constant.SUCCESS == httpRespond.code) {
                                    if (null != httpRespond.data) {
                                        checkComboResponseModel = httpRespond.data;
                                        binding.tvProductPrice.setText(httpRespond.data.getProductPrice());
                                    }
                                    binding.tvConfirmOrder.setBackgroundResource(R.drawable.shape_f93f50_4dp);
                                    binding.tvConfirmOrder.setEnabled(true);
                                    binding.tvConfirmOrder.setText(context.getString(R.string.confirm_place_order));
                                } else {
                                    binding.tvConfirmOrder.setBackgroundResource(R.drawable.shape_d7d7d7_4dp);
                                    binding.tvConfirmOrder.setEnabled(false);
                                    binding.tvConfirmOrder.setText(context.getString(R.string.not_package));
                                }
                                isCanClick = true;
                                mAttrName = attrName;
                                notifyDataSetChanged();
                            }

                            @Override
                            protected void onFail(Throwable e) {
                                isCanClick = true;
                            }
                        });
                    }
                });
            }

            @Override
            public int getItemCount() {
                return list.size();
            }

            class MyHolder extends RecyclerView.ViewHolder {

                private final TextView text;

                public MyHolder(View itemView) {
                    super(itemView);
                    text = itemView.findViewById(R.id.flow_text);
                }
            }
        }

        private int dp2px(float value) {
            return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics());
        }
    }

    public void initLoadingDialog() {
        if (null == loadingDialog) {
            loadingDialog = new LoadingDialog(context);
        }
    }

    public void showLoadingDialog() {
        if (null != loadingDialog) {
            loadingDialog.show();
        }
    }

    public void dismissLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }
}
